package summary;

/**
 * @Author: 海琳琦
 * @Date: 2022/8/30 11:58
 */
public class Title304 {

    private int[][] pre;

    /**
     * 一维前缀和
     * @param matrix
     */
    public Title304(int[][] matrix, int k) {
        int n = matrix.length;
        int m = matrix[0].length;
        pre = new int[n][m + 1];
        int sum = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                pre[i][j] = sum;
                sum += matrix[i][j];
            }
            pre[i][m] = sum;
        }
    }


    /**
     * 二维前缀和
     * @param matrix
     */
    public Title304(int[][] matrix) {
        int n = matrix.length;
        int m = matrix[0].length;
        pre = new int[n + 1][m + 1];
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                pre[i][j] = pre[i - 1][j] + pre[i][j - 1] - pre[i - 1][j - 1] + matrix[i - 1][j - 1];
            }
        }
    }

    public int sumRegion(int row1, int col1, int row2, int col2) {
        return pre[row2 + 1][col2 + 1] - pre[row1][col2 + 1] - pre[row2 + 1][col1] + pre[row1][col1];
    }

    public static void main(String[] args) {

    }
}
